package com.jieshuibao.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.codec.binary.Base64;

import com.jieshuibao.common.config.Global;



public class Base64ForImg {
	public static final String imagesBasePath = Global.getConfig("images.basePath");
	
	// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
	public static String GetImageStr(String imgFilePath) {
		byte[] data = null;
		String s = "";
		// 读取图片字节数组
		try {
			InputStream in = new FileInputStream(imgFilePath);
			data = new byte[in.available()];
			in.read(data);
			in.close();
			// 对字节数组Base64编码
			s = Base64.encodeBase64String(data);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return s;// 返回Base64编码过的字节数组字符串
	}

	// 对字节数组字符串进行Base64解码并生成图片
	public static boolean GenerateImage(String imgStr, String imgFilePath) {
		if (imgStr == null) {// 图像数据为空
			return false;
		}
		try {
			// Base64解码
			byte[] bytes = Base64.decodeBase64(imgStr.getBytes());
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {// 调整异常数据
					bytes[i] += 256;
				}
			}
			// 生成jpeg图片
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(bytes);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	public static  String[] GenerateBach( String[] imgStr,String imgFilePath) {
		String[] str=null;
		if (imgStr == null) {// 图像数据为空
			return str;
		}
		try {
			
			str=new String[imgStr.length];
			int j=1;
			for (String string : imgStr) {
				byte[] bytes = Base64.decodeBase64(string.getBytes());
				for (int i = 0; i < bytes.length; ++i) {
					if (bytes[i] < 0) {// 调整异常数据
						bytes[i] += 256;
					}
				}
				String uuid = UUIDGenerator.getUUID();
				//String uuid = ShortUuid.generateShortUuid();
				String fileName=uuid+j;
				// 生成jpeg图片
				OutputStream out = new FileOutputStream(imagesBasePath+imgFilePath+"/"+fileName);
				out.write(bytes);
				out.flush();
				out.close();
				str[j-1]=fileName;
				j++;
				
			}
			
			return str;
		} catch (Exception e) {
			e.printStackTrace();
			return str;
		}
	}
}